package models

import (
	"errors"
	"fmt"
	"strings"

	"github.com/astaxie/beego/orm"
)

type TApp struct {
	Id          int64  `orm:"column(id);auto" description:""  form:"id"  json:"id"`
	BundleId    string `orm:"column(bundle_id);size(45);null" description:"app 的名称"  form:"bundle_id"  json:"bundle_id"`
	Description string `orm:"column(description);null" description:"app 描述"  form:"description"  json:"description"`
	Platform    int    `orm:"column(platform);null" description:"app 平台"  form:"platform"  json:"platform"`
	Enable      int8   `orm:"column(enable);null" description:"1 为可用，0 为删除。默认为1"  form:"enable"  json:"enable"`
}

func (t *TApp) TableName() string {
	return "t_app"
}
func (t *TApp) TableComment() string {
	return "config app"
}

func init() {
	orm.RegisterModel(new(TApp))
}

// AddTApp insert a new TApp into database and returns
// last inserted Id on success.
func AddTApp(m *TApp) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// GetTAppById retrieves TApp by Id. Returns error if
// Id doesn't exist
func GetTAppById(id int64) (v *TApp, err error) {
	o := orm.NewOrm()
	v = &TApp{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// GetAllTApp retrieves all TApp matches certain condition. Returns empty list if
// no records exist
func GetAllTApp(query map[string]interface{}, fields []string, sortby []string, order []string,
	offset int64, limit int64, needCount bool) (ml []TApp, totalCount int64, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(TApp))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, 0, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, 0, errors.New("Error: unused 'order' fields")
		}
	}

	var l []TApp
	qs = qs.OrderBy(sortFields...)
	if needCount == true {
		if totalCount, err = qs.Count(); err != nil {

			return nil, 0, err
		}
	}
	if limit > 0 {
		qs = qs.Limit(limit, offset)
	}
	if _, err = qs.All(&l); err == nil {

		return l, totalCount, nil
	}
	return nil, totalCount, err
}

// UpdateTApp updates TApp by Id and returns error if
// the record to be updated doesn't exist
func UpdateTAppById(m *TApp) (vo *TApp, err error) {
	o := orm.NewOrm()
	v := TApp{Id: m.Id}
	// ascertain id exists in the database
	//if err = o.Read(&v); err == nil {
	//var num int64
	if _, err = o.Update(m); err == nil {
		return m, nil
		//	fmt.Println("Number of records updated in database:", num)
	}
	//}
	return &v, nil
}

// DeleteTApp deletes TApp by Id and returns error if
// the record to be deleted doesn't exist
func DeleteTApp(id int64) (err error) {
	o := orm.NewOrm()
	v := TApp{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&TApp{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}
